<template>
  <!-- 滑动条组件 -->
  <div class="container" :style="'height: '+slideLineHeight+'px;'">
    <div class="sliding" ref="sliding"></div>
    <span :style="'line-height: '+slideLineHeight+'px;'" ref="text">{{info}}</span>
    <i
      :class="'iconfont ' + icon"
      :style="'line-height: '+slideLineHeight+'px; width: '+iconWidth+'px;'"
      ref="icon"
      @mousedown="iconMove"></i>
  </div>
</template>

<script>
export default {
  name: 'Slide',
  props: {
    // 滑动条高度
    slideLineHeight: {
      type: Number,
      default: 38
    }
  },
  data() {
    return {
      disX: 0, // 滑块移动距离
      iconWidth: 0, // 滑块宽度
      isFinsh: false, // 是否验证成功
      icon: 'icon-arrow-double-right', // 滑块图标
      info: '请向右滑动滑块' // 提示文本
    }
  },
  created() {
    this.iconWidth = this.slideLineHeight * 1.5
  },
  methods: {
    // 滑块移动
    iconMove (e) {
      if (this.isFinsh) {
        return
      }
      let ele = e.target;
			let startX = e.clientX; // 一开始鼠标点击的位置
			let eleWidth = ele.offsetWidth; // 滑块的宽度
			let parentWidth =  ele.parentElement.offsetWidth; // 滑动条宽度
			let MaxX = parentWidth - eleWidth; // 最大可移动的宽度
      document.onmousemove = (e) => {
				let endX = e.clientX; // 鼠标相对以浏览器有效区域的的X轴坐标
				this.disX = endX - startX;
        // 鼠标移出滑动条，滑块在最左边
				if(this.disX<=0){
					this.disX = 0;
				}
				if(this.disX>=MaxX) {
          // 滑块达到右边，验证成功处理
          this.isFinsh = true
					this.disX = MaxX;
          this.$refs.text.style.color = '#fff'
          this.icon = 'icon-success-filling'
          this.$refs.icon.style.color = '#7ac23c'
          this.info='验证成功'
          document.onmousemove = null;
          document.onmouseup = null;
				}
        // 鼠标未滑到终点就松开，滑块回到最左边
        ele.style.transition = null
        this.$refs.sliding.style.transition = null
				ele.style.left = this.disX+'px'
        this.$refs.sliding.style.width = this.disX+'px'
				e.preventDefault();
			}
			document.onmouseup = ()=> {
        // 松开鼠标时，滑块未到达最右边，回到滑动条最左边
        ele.style.transition = '.3s all'
        this.$refs.sliding.style.transition = '.3s all'
        ele.style.left = 0
        this.$refs.sliding.style.width = 0
				document.onmousemove = null;
				document.onmouseup = null;
			}
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  text-align: center;
  position: relative;
  border: 1px solid #eee;
  background-color: #e5e5e5;
  // background: #7ac23c;
  border-radius: 6px;
  overflow: hidden;

  .sliding {
    width: 0;
    height: 100%;
    background: #7ac23c;
    position: absolute;
    left: 0;
    top: 0;
  }

  span {
    position: absolute;
    font-size: 16px;
    width: 100%;
    left: 0;
    top: 0;
    color: #51555c;
  }

  i {
    position: absolute;
    top: 0;
    left: 0;
    font-size: 24px;
    background-color: #fff;
    color: #e5e5e5;
    border-radius: 3px 6px 6px 3px;
    cursor: move;
  }
}
</style>